<?php
// 索引队列
set_time_limit(0);
error_reporting(E_ERROR | E_WARNING | E_PARSE);

include_once('../lib/config.php');
include_once('../lib/Db.class.php');
include_once('../lib/Model.class.php');
include_once('../lib/function.php');
include_once('/usr/local/xunsearch/sdk/php/lib/XS.php');

$redis = new Redis();
$redis->connect(REDIS_IP,"6379");  //php客户端设置的ip及端口
if(!$redis) die('redis connect fail');

$redis->auth(REDIS_PASS);

$GLOBALS['config']['master']['db_database'] = 'suucn';
$GLOBALS['config']['slave']['db_database']  = 'suucn';

$pid = getmypid();
$redis->hSet(MH_PIDS, $pid, date('Y-m-d H:i:s').'||gouyg_queue_index');

$model = new Db;
$model->setForceMaster(true);
$limit = 100;
while ($limit--) {
    $stop = $redis->get('LNPAN_QUEUE_STOP');
    if($stop) {
	    echo 'stop';
        break;
    }

    $max_id = $redis->get('Gouyg_max_index');
    if(!$max_id) {
        $max_info = $model->find("soso", "title is not null", "id desc");
        $max_id   = $max_info['id'];
        $redis->set('Gouyg_max_index', $max_id, 600);
    }

    $min_id = $redis->get('Gouyg_min_index');
    if(!$min_id) {
        $min_id = 405736;
    }
    
    $sql  = "select a.id, a.betype, a.title, a.author, a.sodate, b.content 
            from soso a 
            left join soso_content b on a.id = b.bookid 
            where a.id>'$min_id' and a.id<='$max_id' 
            order by id asc 
            limit 1000";

    $list = $model->query($sql);
    if(!$list) {
	   echo 'empty';
       sleep(2);
	   continue;
    }

    foreach ($list as $item) {
        if(empty($item['title'])) continue;
        
        $index_data = array(
          'id' => $item['id'],
          'title' => $item['title'],
          'content' => $item['content'],
          'addtime' => $item['sodate'],
          'betype' => $item['betype'],
          'author' => $item['author'],
        );

        // 创建文档对象
        $doc = new XSDocument;
        $doc->setFields($index_data);

        // 更新到索引数据库中
        $xs = new XS('gouyg');
        $index  = $xs->index;
        $result = $index->update($doc);

        $min_id = $item['id'];
    }

    $redis->set('Gouyg_min_index', $min_id);

    $xs = new XS('gouyg');
    $index = $xs->index;
    $index->flushIndex();

    $search = $xs->search; //获取搜索对象
    $count = $search->getDbTotal();

    var_dump($min_id, $max_id, $count);

    //break;
}

$model->close();
$redis->hDel(MH_PIDS, $pid);

sleep(5);
